<template>
  <my-container>
    <el-form
      class="ad-form-query"
      :inline="true"
      :model="filter"
      @submit.native.prevent
    >
      <el-form-item
        label="物料类型"
        prop="xbctypeid"
      >
        <el-select
          v-model="filter.wllb"
          filterable
          placeholder="请选择物料类型"
          style="width: 100%;"
          @change="changeValue"
        >
          <el-option
            v-for="item in xbsTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="getDictionaries">查询</el-button>
      </el-form-item> -->
      <!-- <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="insertEvent()"
        >新增</el-button>
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="tcEvent()"
        >入库</el-button>
      </el-form-item>
      <!-- <el-form-item v-if="checkPermission(['api:warehouse:stockin:add'])">
        <el-button
          type="primary"
          icon="el-icon-check"
          @click="saveEvent()"
        >保存</el-button>
      </el-form-item> -->
      <!-- <el-form-item v-if="checkPermission(['api:warehouse:stockin:getpage'])">
        <el-button
          type="primary"
          icon="el-icon-refresh-left"
          @click="getStockInListPage()"
        >刷新</el-button>
      </el-form-item> -->
    </el-form>

    <vxe-modal
      id="edit"
      v-model="modalShow"
      resize
      :destroy-on-close="true"
      remember
      fullscreen
    >
      <template v-slot:title>
        <span>入库:{{ getSelectLabel(filter.wllb, 'value', 'label', xbsTypeList) }}</span>
      </template>
      <template>
        <vxe-toolbar perfect>
          <template v-slot:buttons>
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="insertEvent()"
            >新增</el-button>
            <!-- <vxe-button icon="fa fa-plus" status="perfect" @click="onTaskAdd">新增</vxe-button> -->
            <el-button
              type="primary"
              icon="el-icon-check"
              @click="saveEvent()"
            >保存</el-button>
            <el-button
              type="primary"
              icon="el-icon-refresh-left"
              @click="getStockInListPage()"
            >刷新</el-button>
          </template>
        </vxe-toolbar>

        <vxe-table
          ref="xcTable"
          :loading="loading"
          border
          size="small"
          :keep-source="true"
          :auto-resize="true"
          stripe
          highlight-hover-row
          resizable
          :edit-rules="validRules"
          :data="tableData"
          :edit-config="{
            trigger: 'click',
            mode: 'row',
            activeMethod: activeRowMethod
          }"
          @edit-actived="editActivedEvent"
        >
          <vxe-table-column
            type="seq"
            width="60"
          />
          <vxe-table-column
            field="addStorageBatchCode"
            title="入库批次"
            :edit-render="{ name: 'ElInput', props: { disabled: editDisabled } }"
          />
          <vxe-table-column
            field="xbcMatterrialId"
            title="物料号"
            show-overflow
            :edit-render="{
              name: 'ElSelect',
              options: ptypeList,
              props: { clearable: true, filterable: true },
              events: { change: ptypeChangeEvent }
            }"
          />
          <vxe-table-column
            field="wlms"
            title="物料描述"
            show-overflow
            :edit-render="{ name: 'ElInput', props: { disabled: editDisabled } }"
          />
          <vxe-table-column
            field="wlgg"
            title="物料规格"
            show-overflow
            :edit-render="{ name: 'ElInput', props: { disabled: editDisabled } }"
          />
          <vxe-table-column
            field="dw"
            title="单位"
            :edit-render="{ name: 'ElInput',props: { disabled: editDisabled } }"
          />
          <vxe-table-column
            v-if="!conf.isSingle"
            field="num"
            title="数量"
            :edit-render="{ name: 'ElInputNumber',props: { min: 1} }"
          />
          <vxe-table-column
            field="xbcLocationId"
            title="库位"
            :edit-render="{
              name: 'ElSelect',
              options: locationList,
              props: { clearable: true, filterable: true }
            }"
          />
          <vxe-table-column
            v-if="conf.showCustomCode"
            field="customerCode"
            title="客户代码"
            :edit-render="{ name: 'ElInput', props: { disabled: editDisabled } }"
          />
          <vxe-table-column
            field="addStorageDate"
            title="入库时间"
            show-overflow
            :edit-render="{ name: 'ElDatePicker', props: { type: 'datetime' , format: 'yyyy-MM-dd HH:mm:ss',disabled: editDisabled } }"
          />
          <vxe-table-column
            v-if="conf.isProduceNumb"
            field="materialCode"
            title="物料编码"
            :edit-render="{ name: 'ElInput', props: { disabled: editDisabled } }"
          />
          <vxe-table-column
            v-if="conf.isRegLlBatch"
            field="materialBatchCode"
            show-overflow
            title="来料批次"
            :edit-render="{ name: 'ElInput' }"
          />
          <vxe-table-column
            v-if="conf.isTerm"
            field="effectiveDate"
            title="有效期"
            :edit-render="{name: '$input', props: {type: 'date'}}"
          />
          <vxe-table-column
            v-if="conf.isRegMaterArriDate"
            field="materArriDate"
            title="来料日期"
            :edit-render="{name: '$input', props: {type: 'date'}}"
          />
          <vxe-table-column
            v-if="conf.isRegPcbLot"
            field="pcbLotNum"
            title="PCB LOT号"
            :edit-render="{ name: 'ElInput' }"
          />
          <vxe-table-column
            field="remark"
            title="备注"
            :edit-render="{ name: 'ElInput' }"
          />
        </vxe-table>
        <vxe-pager
          perfect
          :current-page.sync="tablePage.currentPage"
          :page-size.sync="tablePage.pageSize"
          :total="tablePage.total"
          :layouts="[
            'PrevJump',
            'PrevPage',
            'Number',
            'NextPage',
            'NextJump',
            'Sizes',
            'FullJump',
            'Total'
          ]"
          @page-change="pageChangeEvent"
        />
      </template>
    </vxe-modal>
    <!-- <vxe-toolbar>
      <template v-slot:buttons>
        <vxe-button @click="insertEvent()">新增</vxe-button>
      </template>
    </vxe-toolbar> -->

    <!-- <template #footer>
      <vxe-pager
        perfect
        :current-page.sync="tablePage.currentPage"
        :page-size.sync="tablePage.pageSize"
        :total="tablePage.total"
        :layouts="[
          'PrevJump',
          'PrevPage',
          'Number',
          'NextPage',
          'NextJump',
          'Sizes',
          'FullJump',
          'Total'
        ]"
        @page-change="pageChangeEvent"
      />
    </template> -->
  </my-container>
</template>

<script>
import XEUtils from 'xe-utils'
import { getxbcTypeList, getXbcTypeConf } from '@/api/warehouse/xbctype'
import { getxbcLocationList } from '@/api/warehouse/xbclocation'
import { getMaterList, getMaterInfo, addStockIn, getStockInListPage } from '@/api/warehouse/stockin'
import MyContainer from '@/components/my-container'
export default {
  name: 'Mater',
  components: { MyContainer },
  data() {
    return {
      conf: {
        isTerm: false, // 是否有效期
        isRegLlBatch: false, // 是否记录来料批次
        isSingle: false, // 是否单个入库
        isProduceNumb: false, // 是否生成编号
        prefix: '', // 编号前缀
        canReturn: false, // 是否要归还
        isThawWare: false, // 是否有解冻仓库
        isRegEquip: false, // 出库是否记录设备号
        isRegProduBatch: false, // 是否记录产品批号
        isRegMaterArriDate: false, // 是否记录来料日期
        isRegPcbLot: false, // 是否等级pcblot号
        showCustomCode: false // 是否显示客户代码
      },
      modalShow: false,
      loading: false,
      xbsTypeList: [], // 物料下拉
      tabsList: [],
      filter: {
        wllb: '' // 物料类别
      },
      editDisabled: false,
      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 10
      },
      validRules: {
        // xbcMatterrialId: [
        //   { required: true, message: '物料号不可为空' }
        // ],
        // xbcLocationId: [
        //   { required: true, message: '库位不可为空' }
        // ],
        // materArriDate: this.conf.isRegMaterArriDate
        //   ? [{ required: true, message: '来料日期不可为空' }]
        //   : []
      },
      // flag: 0,
      tableData: [],
      ptypeList: [],
      locationList: [],
      cachePnameList: []
    }
  },
  mounted() {
    this.getxbcTypeList()
  },
  created() { },
  methods: {
    insertEvent() {
      if (this.filter.wllb === '') {
        this.$XModal.message({ status: 'warning', message: '请选择物料类型！' })
      } else {
        var record = {}
        this.$refs.xcTable.insert(record)
      }
    },
    getDatePicker(value) {
      return XEUtils.toDateString(value, 'yyyy/MM/dd')
    },
    getSelectLabel(value, valueProp, labelProp, list) {
      const item = XEUtils.find(list, item => item[valueProp] === value)
      return item ? item[labelProp] : null
    },
    async getStockInListPage() {
      const para = {
        currentPage: this.tablePage.currentPage,
        pageSize: this.tablePage.pageSize,
        filter: this.filter
      }
      this.loading = true
      const res = await getStockInListPage(para)
      this.loading = false

      if (!res?.success) {
        return
      }

      this.tablePage.total = res.data.total
      const data = res.data.list
      this.tableData = data
    },
    async loadData() {
      await this.getStockInListPage()
    },

    async tcEvent() {
      if (this.filter.wllb === '') {
        this.$XModal.message({ status: 'warning', message: '请选择物料类型！' })
      } else {
        this.modalShow = !this.modalShow
        const res = await getMaterList({ id: this.filter.wllb })
        const res1 = await getxbcLocationList({ id: this.filter.wllb })
        const res2 = await getXbcTypeConf({ id: this.filter.wllb })
        if (res2 && res2.success) {
          this.conf = res2.data
        }
        if (res && res.success) {
          this.ptypeList = res.data
        }
        if (res1 && res1.success) {
          this.locationList = res1.data
        }
        this.validRules = {
          xbcMatterrialId: [
            { required: true, message: '物料号不可为空' }
          ],
          xbcLocationId: [
            { required: true, message: '库位不可为空' }
          ]
        }
        if (this.conf.isRegMaterArriDate) {
          this.$set(this.validRules, 'materArriDate', [{ required: true, message: '来料日期不可为空' }])
        }

        if (this.conf.isTerm) {
          this.$set(this.validRules, 'effectiveDate', [{ required: true, message: '有效期不可为空' }])
        }
        if (this.conf.isRegLlBatch) {
          this.$set(this.validRules, 'materialBatchCode', [{ required: true, message: '来料批次不可为空' }])
        }
        await this.loadData()
      }
    },

    async changeValue() {
      // const res = await getMaterList({ id: this.filter.wllb })
      // const res1 = await getxbcLocationList({ id: this.filter.wllb })
      // const res2 = await getXbcTypeConf({ id: this.filter.wllb })
      // if (res2 && res2.success) {
      //   this.conf = res2.data
      // }
      // if (res && res.success) {
      //   this.ptypeList = res.data
      // }
      // if (res1 && res1.success) {
      //   this.locationList = res1.data
      // }
      // this.validRules = {
      //   xbcMatterrialId: [
      //     { required: true, message: '物料号不可为空' }
      //   ],
      //   xbcLocationId: [
      //     { required: true, message: '库位不可为空' }
      //   ]
      // }
      // if (this.conf.isRegMaterArriDate) {
      //   this.$set(this.validRules, 'materArriDate', [{ required: true, message: '来料日期不可为空' }])
      // }

      // if (this.conf.isTerm) {
      //   this.$set(this.validRules, 'effectiveDate', [{ required: true, message: '有效期不可为空' }])
      // }
      // if (this.conf.isRegLlBatch) {
      //   this.$set(this.validRules, 'materialBatchCode', [{ required: true, message: '来料批次不可为空' }])
      // }
      // await this.loadData()
    },
    activeRowMethod({ row, rowIndex }) {
      return row.addStorageBatchCode === null
    },
    editActivedEvent({ rowIndex, row }) {
      this.editDisabled = row.addStorageBatchCode === null
    },
    async getxbcTypeList() {
      const res = await getxbcTypeList()
      if (res && res.success) {
        this.xbsTypeList = res.data
      }
    },
    // 格式化显示名称
    formatPanmeLabel({ cellValue, row }) {
      var ptype = row.attr3
      var ptypeItem = this.cachePnameList.find(item => item.ptype === ptype)
      if (ptypeItem && ptypeItem.pnameList) {
        var pnameItem = ptypeItem.pnameList.find(
          item => item.value === cellValue
        )
        if (pnameItem) {
          return pnameItem.label
        }
      }
      return ''
    },
    async saveEvent() {
      const errMap = await this.$refs.xcTable.validate().catch(errMap => errMap)
      if (errMap) {
        this.$XModal.message({ status: 'error', message: '校验不通过！' })
      } else {
        const {
          insertRecords,
          // eslint-disable-next-line no-unused-vars
          removeRecords,
          // eslint-disable-next-line no-unused-vars
          updateRecords
        } = this.$refs.xcTable.getRecordset()
        // console.log(insertRecords)
        if (insertRecords.length !== 0) {
          await addStockIn(insertRecords)
          this.$message({
            message: this.$t('admin.addOk'),
            type: 'success'
          })
          // 刷新
          await this.getStockInListPage()
          // this.$XModal.alert(insertRecords)
        } else {
          this.$XModal.message({ status: 'warning', message: '没有新增数据！' })
        }
      }
    },
    async pageChangeEvent() {
      await this.getStockInListPage()
    },
    // 更新级联选项列表
    updatePnameList(row) {
      var ptype = row.attr3
      var pnameList = []
      if (ptype) {
        var item = this.cachePnameList.find(item => item.ptype === ptype)
        if (item) {
          pnameList = item.pnameList
        } else {
          // 模拟后台数据
          Array.from(new Array(XEUtils.random(3, 8))).forEach((item, index) => {
            pnameList.push({
              label: `${ptype}-名称${index}`,
              value: `${ptype}_${index}`
            })
          })
          this.cachePnameList.push({ ptype, pnameList })
        }
      }
      console.log(pnameList)
      // this.pnameList = pnameList
    },
    async ptypeChangeEvent({ row }) {
      // 类型切换时更新级联的下拉数据
      var res = await this.getMaterInfo(row.xbcMatterrialId)
      if (res && res.success) {
        row.wlms = res.data.wlms
        row.customerCode = res.data.customerCode
        row.xbcLocationId = res.data.xbcLocationId
        row.wlgg = res.data.wlgg
        row.dw = res.data.dw
      }
    },
    async getMaterInfo(id) {
      return await getMaterInfo({ id: id })
    }
  }
}
</script>
